package com.wlf.ServiceImpl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.wlf.Entity.SalesForecastTable;
import com.wlf.Mapper.ExcelMapper;
import com.wlf.Service.ExcelService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class ExcelServiceImpl implements ExcelService {

    @Autowired
    private ExcelMapper excelMapper;

    //获取数据库中数据
    @Override
    public List<SalesForecastTable> getAll() {
        return excelMapper.getAll();
    }

    //导出excel
    public void exportExcel(HttpServletResponse response) throws IOException {
        try{
            //获取所以数据
            List<SalesForecastTable> salesForecastTables=excelMapper.getAll();
            //过滤掉numberB为0的数据
            List<SalesForecastTable> filteredData = salesForecastTables.stream()
                    .filter(data -> !StringUtils.equals(data.getNumberB(),"0"))
                    .collect(Collectors.toList());
            //写入文件
            EasyExcel.write(response.getOutputStream(),SalesForecastTable.class)
                    .sheet("Sheet1")
                    .doWrite(filteredData);
            //清空数据库salesForecastTables表的数据
            /*excelMapper.deleteInfo();*/
        }catch (Exception e){
            throw new RuntimeException("Excel文件写入失败",e);
        }
    }
    //导入excel
    @Override
    public void importExcel(MultipartFile file) {
        try(InputStream inputStream= file.getInputStream()){
            EasyExcel.read(inputStream, SalesForecastTable.class, new ReadListener<SalesForecastTable>() {
                //    单次缓存的数据量
                public static final int BATCH_COUNT = 100;
                //    临时存储
                private List<SalesForecastTable> cachedDataList  = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
                @Override
                public void invoke(SalesForecastTable salesForecastTable, AnalysisContext analysisContext) {
                    cachedDataList.add(salesForecastTable);
                    // 当缓存列表中的数据数量达到批量处理的条件时，执行数据存储操作
                    if (cachedDataList.size() >= BATCH_COUNT) {
                        saveData();
                        // 存储完成清理 list
                        cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
                    }
                }
                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                    if(!cachedDataList.isEmpty()){
                        saveData();
                    }
                    System.out.println("所有数据以及读取完成并存储到数据库中");
                }
                private void saveData() {
                    //保存到数据库
                    int rowsAffected = excelMapper.saveList(cachedDataList);
                    if(rowsAffected>0){
                        System.out.println("成功保存了");
                    }else{
                        System.out.println("没有数据被保存到数据库");
                    }
                }
            }).sheet().doRead();
        } catch (IOException e) {
            throw new RuntimeException("Excel文件读取失败",e);
        }
    }

    //清空数据库SalesForecastTable表中数据
    @Override
    public void deleteInfo() {
        excelMapper.deleteInfo();
    }

}
